﻿using System;
using Microsoft.Office.Interop.Word;

namespace Songhay.Office2010.Word
{
    /// <summary>
    /// Static members for <see cref="Microsoft.Office.Interop.Word.Range"/>.
    /// </summary>
    public static class RangeUtility
    {
        /// <summary>
        /// Gets the open XML.
        /// </summary>
        /// <param name="rangeObject">The range object.</param>
        /// <returns>Returns a well-formed Open XML <see cref="System.String"/>.</returns>
        /// <remarks>
        /// “The Range.WordXml object returns a Flat OPC XML document
        /// for that range as a string. You use this to prepare an in-memory package
        /// so that your code can access necessary parts such as the main document part,
        /// the styles part, and the numbering part.”
        /// 
        /// —Anil Kumar, Ansari M, Sarang Datye, Sunil Kumar
        /// 
        /// “Using Open XML to Improve Automation Performance
        /// in Word 2010 for Large Amounts of Data”
        /// (http://msdn.microsoft.com/en-us/library/ff191178.aspx)
        /// </remarks>
        public static string GetOpenXml(Range rangeObject)
        {
            if(rangeObject == null) throw new ArgumentNullException("rangeObject", "The Word Range is null");

            var xml = string.Empty;

            xml = rangeObject.WordOpenXML;

            return xml;
        }

        /// <summary>
        /// Gets the range.
        /// </summary>
        /// <param name="wordDocument">The word document.</param>
        /// <param name="defaultToWholeDocument">if set to <c>true</c> default to whole document Range.</param>
        /// <returns>Returns <see cref="Microsoft.Office.Interop.Word.Range"/>.</returns>
        public static Range GetRange(Document wordDocument, bool defaultToWholeDocument = true)
        {
            if(wordDocument == null) throw new ArgumentNullException("wordDocument", "The Word Document is null");

            var application = wordDocument.Application;
            var range = application.Selection.Range;

            if((application.Selection.Type == WdSelectionType.wdSelectionIP) && defaultToWholeDocument)
            {
                range = wordDocument.Range(Start: 0, End: wordDocument.Characters.Count);
            }
            else if(application.Selection.Range != null)
            {
                range = application.Selection.Range;
            }

            return range;
        }
    }
}
